package com.solarStruggle.domain

import java.awt.{Color, Point}
import graphics.{ImageGenerator, ColorSpec, RandomColorDescriptor, BufferedImage, ProceduralImageGenerator, StarField, LayeredImageGenerator, MetaBallGenerator}

object SolarSystem {
  
  def apply(size: Int, x: Int, y: Int): SolarSystem = {
    val r = new Random()
    val image = new SolarSystemImageGenerator(64 * size, 64 * size).createImage()
    new SolarSystem(getRandomName(), image, x, y, Array(Array[SolarSystemTile]()))
  }
  
  def getRandomName(): String = {
    val names = Array("Sol", "Sirius", "Canopus", "Arcturus", "Alpha Centauri", "Vega", "Rigel", "Procyon",
    "Achernar", "Betelgeuse", "Agena", "Capella", "Altair", "Aldebaran", "Spica", "Antares", "Pollux", 
    "Fomalhaut", "Deneb", "Mimosa", "Regulus", "Acrux", "Adara", "Shaula", "Gacrux", "Bellatrix",
    "El Nath", "Miaplacidus", "Alnilam", "Alnitak", "Al Na'ir", "Alioth", "Velorum", "Kaus Australis",
    "Mirfak", "Wezen", "Alkaid", "Sargas", "Dubhe", "Alhena", "Peacock", "Atria", "Castor", "Murzim",
    "Alphard", "Hamal", "Polaris", "Delta Velorum", "Deneb Kaitos", "Saiph", "Nunki", "Menkent", "Alpheratz",
    "Mirach", "Kochab", "Acrux", "Ras Alhague", "Algol", "Beta Gruis", "Denebola", "Zeta Puppis", 
    "Lambda Velorum", "Etamin", "Alphecca", "Sadr", "Schedar", "Aspidiske", "Almach", "Mizar", "Caph",
    "Epsilon Centauri", "Algieba", "Alpha Lupi", "Wei", "Eta Centauri", "Merak", "Ankaa", "Girtab", 
    "Gamma Cassiopeiae", "Enif", "Aludra", "Avior", "Scheat", "Phecda", "Alderamin", "Kappa Velorum",
    "Markab", "Gienah")
    return names(new Random().nextInt(names.length))
  }
}

@serializable
class SolarSystem(val name: String, val image: BufferedImage, val x: Int, val y: Int, val tiles: Array[Array[SolarSystemTile]])

class SolarSystemImageGenerator(width: Int, height: Int)
extends ImageGenerator(width, height) {
  
  val r = new Random()
  
  override def createImage(): BufferedImage = {
    val img = new BufferedImage(width, height)
    
    val stars = new StarField(width, height, r.nextInt(6), Color.BLACK, 
      RandomColorDescriptor(ColorSpec(Color.WHITE, (-0.5f, 0.0f), ColorSpec.VaryBy(0.1f), ColorSpec.Invariant),
        (0.025f, ColorSpec(new Color(0.2f, 0.2f, 0.7f), (-0.4f, -0.8f), ColorSpec.VaryBy(0.05f), ColorSpec.Invariant)),
        (0.025f, ColorSpec(new Color(0.7f, 0.2f, 0.2f), (-0.7f, 0.0f), ColorSpec.VaryBy(0.05f), ColorSpec.Invariant)))    
    ).createImage
    
    val sunRadius = r.nextInt(2) + 1
    val sun = new MetaBallGenerator(width, height, new Color(0, 0, 0, 0), 1, (Math.min(1.0, sunRadius / 3.0) * 64.0).toInt, sunRadius * 64, new Point(width / 2, height / 2) :: Nil) {
      override def colorFunction(value: Float) = new Color(Math.min(1.0f, value * 1.5f).toFloat, Math.min(1.0f, value * 1.5f).toFloat, value, if(value > 0.05) 1.0f else 0.0f)
    }.createImage
    
    new LayeredImageGenerator(stars :: sun :: Nil).createImage
  }
}
